package com.jml.手写日志框架.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;


@Slf4j
@Component
public class StartListener implements ApplicationListener<ApplicationReadyEvent> {
    //项目启动成功后就会调用这个方法，这个线程会创建一个新的线程，新线程就一直执行一直去获取队列中的日志信息
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        log.info("当前项目启动成功");
        start();
    }
    public void start() {
        Worker worker = new Worker();
        //单独开启一个线程异步写日志
        worker.start();
    }
    class Worker extends Thread {
        @Override
        public void run() {
            for (; ; ) {
                //死循环获取队列数据
                String mtLog = LogBlockingQueue.getLog();
                if (!StringUtils.isEmpty(mtLog)) {
                    //将队列中的日志内容写入到硬盘中
                    LogException.writeErrorMsg(mtLog);
                    log.info("采用日志队列异步写入日志:{}", mtLog);
                }
            }
        }
    }
}
